<?php
/**
 * 熵巡 - 企业级氚云OpenAPI数据管理平台
 * 开发归属 Alyr.net
 * 数据查询功能接口 - 实时查询表单数据
 * 尊重劳动成果是一种美德
 */

date_default_timezone_set('Asia/Shanghai');
ini_set('display_errors', 0);
error_reporting(0);
ini_set('session.save_path', sys_get_temp_dir());
session_start();

// 日志函数已禁用
// function writeQueryLog($message, $level = 'INFO') {}

if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => '请先登录'], JSON_UNESCAPED_UNICODE);
    exit;
}

header('Content-Type: application/json; charset=utf-8');

$action = $_GET['action'] ?? $_POST['action'] ?? '';

if ($action === 'query_data') {
    try {
        // writeQueryLog('=== 数据查询请求开始 ===');
        
        require_once '../config.php';
        require_once '../classes/H3OpenApiClient.php';
        
        $config = require '../config.php';
        $client = new H3OpenApiClient($config);
        
        // 获取过滤参数
        $schemaKey = $_GET['schema_key'] ?? 'default';
        $dateType = $_GET['date_type'] ?? 'today';
        $startDate = $_GET['start_date'] ?? date('Y-m-d');
        $endDate = $_GET['end_date'] ?? date('Y-m-d');
        $dataLimit = intval($_GET['data_limit'] ?? 1000);
        $sortOrder = $_GET['sort_order'] ?? 'desc';
        
        // writeQueryLog("查询参数 - Schema: {$schemaKey}, 日期范围: {$startDate} ~ {$endDate}, 数量限制: {$dataLimit}");
        
        // 获取对应表单的配置
        $schemas = $config['schemas'] ?? [];
        if (!isset($schemas[$schemaKey])) {
            // writeQueryLog("错误: 表单不存在 - {$schemaKey}", 'ERROR');
            throw new Exception('表单不存在');
        }
        $schemaConfig = $schemas[$schemaKey];
        $schemaCode = $schemaConfig['schema_code'];
        $imageFields = $schemaConfig['image_fields'] ?? [];
        $attachmentFields = $schemaConfig['attachment_fields'] ?? [];
        
        // writeQueryLog("使用表单配置 - Code: {$schemaCode}, 图片字段: " . count($imageFields) . ", 附件字段: " . count($attachmentFields));
        
        // 验证数据限制
        if ($dataLimit > 5000) {
            $dataLimit = 5000; // 查询最大5000条
        }
        
        // 查询指定时间范围的数据
        $todayStart = $startDate . ' 00:00:00';
        $todayEnd = $endDate . ' 23:59:59';
        
        $filter = [
            'FromRowNum' => 0,
            'ToRowNum' => $dataLimit,
            'RequireCount' => true,
            'ReturnItems' => [],
            'SortByCollection' => [
                [
                    'ItemName' => 'CreatedTime',
                    'Direction' => $sortOrder === 'asc' ? 'Ascending' : 'Descending'
                ]
            ],
            'Matcher' => [
                'Type' => 'And',
                'Matchers' => [
                    [
                        'Type' => 'ItemMatcher',
                        'ItemName' => 'CreatedTime',
                        'Operator' => 'GreaterThanOrEqual',
                        'Value' => $todayStart
                    ],
                    [
                        'Type' => 'ItemMatcher',
                        'ItemName' => 'CreatedTime',
                        'Operator' => 'LessThanOrEqual',
                        'Value' => $todayEnd
                    ]
                ]
            ]
        ];
        
        $result = $client->loadBizObjects($schemaCode, $filter);
        
        if (empty($result)) {
            echo json_encode([
                'success' => true,
                'message' => '暂无数据',
                'data' => [],
                'total_count' => 0,
                'query_date' => $dateType === 'today' ? date('Y/m/d') : "$startDate 至 $endDate"
            ], JSON_UNESCAPED_UNICODE);
            exit;
        }
        
        // 处理数据并过滤指定日期范围的数据
        $processedData = [];
        
        foreach ($result as $item) {
            $createdTime = $item['CreatedTime'] ?? '';
            
            // 验证是否在指定日期范围内
            if (!empty($createdTime)) {
                $itemDate = date('Y-m-d', strtotime($createdTime));
                if ($itemDate < $startDate || $itemDate > $endDate) {
                    continue;
                }
            }
            
            $processedItem = [
                'id' => $item['ObjectId'] ?? '',
                'title' => $item['Name'] ?? '无标题',
                'seq_no' => $item['SeqNo'] ?? '',  // 流水号/内部单号
                'created_time' => $createdTime,
                'image_fields' => [],
                'all_fields' => []
            ];
            
            // 处理所有字段，不排除任何字段
            foreach ($item as $fieldCode => $value) {
                $isImage = in_array($fieldCode, $imageFields);
                $isAttachment = in_array($fieldCode, $attachmentFields);
                
                // 正确处理字段值的显示
                $displayValue = '';
                if (is_null($value) || $value === '') {
                    $displayValue = '空';
                } else if (is_array($value) || is_object($value)) {
                    $displayValue = json_encode($value, JSON_UNESCAPED_UNICODE);
                } else {
                    $displayValue = (string)$value;
                }
                
                $processedItem['all_fields'][$fieldCode] = [
                    'field_name' => $fieldCode,
                    'field_code' => $fieldCode,
                    'raw_value' => $value,
                    'display_value' => $displayValue,
                    'is_image' => $isImage,
                    'is_attachment' => $isAttachment
                ];
                
                // 如果是图片字段，添加到图片字段数组
                if ($isImage) {
                    $processedItem['image_fields'][] = [
                        'field_code' => $fieldCode,
                        'field_name' => $fieldCode,
                        'value' => $value
                    ];
                }
            }
            
            $processedData[] = $processedItem;
        }
        
        $totalCount = count($processedData);
        // writeQueryLog("查询成功 - 返回数据: {$totalCount} 条");
        // writeQueryLog('=== 数据查询请求结束 ===');
        
        echo json_encode([
            'success' => true,
            'message' => '当日数据查询成功',
            'data' => $processedData,
            'total_count' => $totalCount,
            'query_date' => date('Y/m/d'),
            'schema_code' => $schemaCode
        ], JSON_UNESCAPED_UNICODE);
        
    } catch (Exception $e) {
        $errorMsg = $e->getMessage();
        // writeQueryLog("查询异常: {$errorMsg}", 'ERROR');
        // writeQueryLog('=== 数据查询请求异常结束 ===');
        
        echo json_encode([
            'success' => false,
            'message' => '查询异常: ' . $errorMsg
        ], JSON_UNESCAPED_UNICODE);
    }
} else {
    echo json_encode(['success' => false, 'message' => '无效的操作'], JSON_UNESCAPED_UNICODE);
}
?>